package com.whfc.ms.api.emp.service.impl;

import com.alibaba.fastjson.JSON;
import com.whfc.common.enums.AppType;
import com.whfc.common.exception.BizException;
import com.whfc.common.face.aiot.AiotApiResult;
import com.whfc.common.face.aiot.AiotCode;
import com.whfc.common.face.aiot.AiotFaceApi;
import com.whfc.common.file.FileHandler;
import com.whfc.common.file.FilePathConfig;
import com.whfc.common.result.PageData;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.util.ImageUtil;
import com.whfc.common.util.RandomUtil;
import com.whfc.common.weixin.bean.OAuthAccessToken;
import com.whfc.common.weixin.bean.OAuthUserInfo;
import com.whfc.common.weixin.mp.OAuth2Api;
import com.whfc.emp.dto.AppFaceGateVisitorCheckDTO;
import com.whfc.emp.dto.AppFaceGateVisitorDTO;
import com.whfc.emp.dto.AppFaceGateVisitorNumDTO;
import com.whfc.emp.param.AppFaceGateVisitorAddParam;
import com.whfc.emp.param.AppFaceGateVisitorCheckAddParam;
import com.whfc.emp.param.AppFaceGateVisitorCheckParam;
import com.whfc.emp.service.AppFaceGateVisitorService;
import com.whfc.entity.dto.OssPathDTO;
import com.whfc.fuum.dto.WxConfigDTO;
import com.whfc.fuum.service.WxConfigService;
import com.whfc.ms.api.emp.service.MsAppFaceGateVisitorService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.io.ByteArrayInputStream;
import java.util.Date;

/**
 * @ClasssName MsAppFaceGateVisitorServiceImpl
 * @Description 访客审核
 * @Author hw
 * @Date 2021/2/27 8:49
 * @Version 1.0
 */
@Service
public class MsAppFaceGateVisitorServiceImpl implements MsAppFaceGateVisitorService {

    @DubboReference(interfaceClass = AppFaceGateVisitorService.class, version = "1.0.0")
    private AppFaceGateVisitorService appFaceGateVisitorService;

    @DubboReference(interfaceClass = WxConfigService.class, version = "1.0.0")
    private WxConfigService wxConfigService;

    @Autowired
    private FilePathConfig filePathConfig;

    @Autowired
    private FileHandler fileHandler;

    @Override
    public PageData<AppFaceGateVisitorDTO> list(Integer deptId, Integer pageSize, Integer pageNum, Integer state, Date startTime, Date endTime) {
        return appFaceGateVisitorService.list(deptId, pageSize, pageNum, state, startTime, endTime);
    }

    @Override
    public void add(AppFaceGateVisitorAddParam request) {
        String pictureData = request.getPictureData();
        String pictureUrl = uploadImg(pictureData);
        if (StringUtils.isEmpty(pictureUrl)) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "访客头像上传失败");
        }
        request.setPictureUrl(pictureUrl);
        request.setPictureData(null);
        appFaceGateVisitorService.add(request);
    }

    @Override
    public void check(AppFaceGateVisitorCheckParam request) {
        appFaceGateVisitorService.check(request);
    }

    @Override
    public OssPathDTO export(Integer deptId, Integer state, Date startTime, Date endTime) {
        return appFaceGateVisitorService.export(deptId, state, startTime, endTime);
    }

    @Override
    public AppFaceGateVisitorNumDTO getNum(Integer deptId, Date startTime, Date endTime) {
        return appFaceGateVisitorService.getNum(deptId, startTime, endTime);
    }

    @Override
    public void del(Integer visitorId) {
        appFaceGateVisitorService.del(visitorId);
    }

    @Override
    public AppFaceGateVisitorCheckDTO checkAdd(AppFaceGateVisitorCheckAddParam request) {
        String openId = request.getOpenid();
        if (StringUtils.isEmpty(openId)) {
            OAuthUserInfo userInfo = getUserInfoByCode(AppType.FCWL, request.getCode());
            request.setOpenid(userInfo.getOpenid());
        }
        return appFaceGateVisitorService.checkAdd(request);
    }


    private OAuthUserInfo getUserInfoByCode(AppType appType, String code) {
        WxConfigDTO configDTO = getWxConfig(appType);
        String response = OAuth2Api.accessToken(configDTO.getAppId(), configDTO.getAppSecret(), code);
        OAuthAccessToken token = JSON.parseObject(response, OAuthAccessToken.class);
        if (token == null || StringUtils.isEmpty(token.getOpenid())) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "微信oauth授权失败");
        }
        response = OAuth2Api.userInfo(token.getAccessToken(), token.getOpenid());
        OAuthUserInfo userInfo = JSON.parseObject(response, OAuthUserInfo.class);
        if (userInfo == null || StringUtils.isEmpty(userInfo.getOpenid())) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "微信oauth授权失败");
        }
        return userInfo;
    }

    /**
     * 获取微信配置
     *
     * @param appType
     * @return
     */
    private WxConfigDTO getWxConfig(AppType appType) {
        WxConfigDTO configDTO = wxConfigService.getWxConfig(appType.name(), false);
        if (ObjectUtils.isEmpty(configDTO) || StringUtils.isEmpty(configDTO.getAppId()) || StringUtils.isEmpty(configDTO.getAppSecret())) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "获取sessionKey失败,小程序配置参数错误");
        }
        return configDTO;
    }

    /**
     * 上传图片
     *
     * @param base64Str
     * @return
     */
    private String uploadImg(String base64Str) {
        String path = filePathConfig.getFilePath("emp/visitor/image", RandomUtil.getRandomFileName(), "png");
        AiotApiResult<String> result = AiotFaceApi.detect(null, base64Str);
        if (!AiotCode.OP_SUS_1000.getValue().equals(result.getCode())) {
            String message = AiotCode.parseByValue(result.getCode());
            throw new BizException(ResultEnum.FAILURE.getCode(), message);
        }
        //base64上传
        byte[] imageByte = ImageUtil.base64ToImage(base64Str);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(imageByte);
        return fileHandler.upload(path, inputStream);

    }
}
